<template>
  <div>
    <el-tabs v-model="activeName">
      <el-tab-pane label="中文" name="first">
        <el-form ref="form" :model="form" label-width="160px">
          <el-form-item label="活动名称">
            <el-input v-model="form.activityName"></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="form.sort"></el-input>
          </el-form-item>
          <el-form-item label="活动开始时间" v-if="activityType != 1">
            <el-date-picker
              v-model="form.activityStartTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="活动开始时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预约开始时间" v-if="activityType != 1">
            <el-date-picker
              v-model="form.activityReservationStartTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="预约开始时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预约结束时间" v-if="activityType != 1">
            <el-date-picker
              v-model="form.activityReservationEndTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="预约结束时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="三级菜单" v-if="activityType != 1">
            <el-select v-model="form.activityMenuId" placeholder="请选择三级菜单">
              <el-option
                v-for="item in activityMenuList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="WAP端封面">
            <FileUpload
              :limit="1"
              v-model="form.wapImgUrl"
              :fileType="['jpg', 'jpeg', 'png']"
            />
          </el-form-item>
          <el-form-item label="PC端封面">
            <FileUpload
              :limit="1"
              v-model="form.pcImgUrl"
              :fileType="['jpg', 'jpeg', 'png']"
            />
          </el-form-item>
          <el-form-item
            :label="activityType != 1 ? '预约须知' : '排队取号须知'"
          >
            <el-input type="textarea" v-model="form.queuingInstructions" />
          </el-form-item>
          <el-form-item label="活动介绍">
            <div ref="editorContainer"></div>
            <!-- <el-input type="textarea" v-model="form.activityIntroduce" /> -->
          </el-form-item>
          <el-form-item label="活动地点">
            <el-input type="textarea" v-model="form.activityPlace"></el-input>
          </el-form-item>
          <el-form-item label="是否亲子活动" v-if="activityType != 1">
            <el-radio-group v-model="form.isParentChild">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否收费" v-if="activityType != 1">
            <el-radio-group v-model="form.isCharge">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="英文" name="second">
        <el-form ref="form" :model="form" label-width="160px">
          <el-form-item label="活动名称">
            <el-input v-model="form.activityNameEn"></el-input>
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="form.sort"></el-input>
          </el-form-item>
          <el-form-item label="活动开始时间" v-if="activityType != 1">
            <el-date-picker
              v-model="form.activityStartTime"
              type="datetime"
              value-format="YYYY-MM-dd HH:mm:ss"
              placeholder="活动开始时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预约开始时间" v-if="activityType != 1">
            <el-date-picker
              v-model="form.activityReservationStartTime"
              type="datetime"
              value-format="YYYY-MM-dd HH:mm:ss"
              placeholder="预约开始时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="预约结束时间" v-if="activityType != 1">
            <el-date-picker
              v-model="form.activityReservationEndTime"
              type="datetime"
              value-format="YYYY-MM-dd HH:mm:ss"
              placeholder="预约结束时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="三级菜单" v-if="activityType != 1">
            <el-select v-model="form.activityMenuId" placeholder="请选择三级菜单">
              <el-option
                v-for="item in activityMenuList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="WAP端封面">
            <FileUpload
              :limit="1"
              :value="form.wapImgUrl"
              :fileType="['jpg', 'jpeg', 'png']"
            />
          </el-form-item>
          <el-form-item label="PC端封面">
            <FileUpload
              :limit="1"
              :value="form.pcImgUrl"
              :fileType="['jpg', 'jpeg', 'png']"
            />
          </el-form-item>
          <el-form-item label="排队取号须知">
            <el-input type="textarea" v-model="form.queuingInstructionsEn" />
          </el-form-item>
          <el-form-item label="活动介绍">
            <div ref="editorContainerEn"></div>
          </el-form-item>
          <el-form-item label="活动地点">
            <el-input type="textarea" v-model="form.activityPlaceEn"></el-input>
          </el-form-item>
          <el-form-item label="是否亲子活动" v-if="activityType !== 1">
            <el-radio-group v-model="form.isParentChild">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否收费" v-if="activityType != 1">
            <el-radio-group v-model="form.isCharge">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <h3>场次管理</h3>
    <el-button type="primary" @click="onAdd">新增</el-button>

    <el-table :data="form.activityTimeList">
      <el-table-column
        label="场次名称"
        prop="activityTimeName"
      ></el-table-column>
      <el-table-column
        label="英文场次名称"
        prop="activityTimeNameEn"
      ></el-table-column>
      <el-table-column
        label="活动起始时间"
        prop="activityBeginTime"
      ></el-table-column>
      <el-table-column
        label="活动结束时间"
        prop="activityEndTime"
      ></el-table-column>
      <el-table-column
        label="取号起始时间"
        prop="queueBeginTime"
        v-if="activityType == 1"
      ></el-table-column>
      <el-table-column
        label="取号结束时间"
        prop="queueEndTime"
        v-if="activityType == 1"
      ></el-table-column>
      <el-table-column label="限制人数" prop="limitPeopleNum"></el-table-column>
      <el-table-column label="限制入场年龄" v-if="activityType != 1">
        <template slot-scope="scope">
          <span>{{ scope.row.minAge + "-" + scope.row.maxAge }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-link
            style="margin: 0 2px"
            type="primary"
            @click="onEdit(scope.row, scope.$index)"
            >编辑</el-link
          >
          <el-link
            style="margin: 0 2px"
            type="primary"
            @click="onDelete(scope.$index)"
            >删除</el-link
          >
        </template>
      </el-table-column>
    </el-table>
    <template v-if="form.id">
      <h3>审批记录</h3>
      <el-table :data="actionLogList" stripe style="width: 100%" height="350">
        <el-table-column type="index" label="序号" width="60" align="center">
        </el-table-column>
        <el-table-column prop="actionCode" label="当前状态" width="80">
        </el-table-column>
        <el-table-column prop="actionRoleName" label="岗位" width="90">
        </el-table-column>
        <el-table-column prop="actionUserName" label="人员" width="120">
        </el-table-column>
        <el-table-column prop="actionAt" label="操作时间" width="140">
        </el-table-column>
        <el-table-column prop="actionText" label="操作" width="100">
        </el-table-column>
        <el-table-column prop="actionNote" label="审核意见"> </el-table-column>
      </el-table>
    </template>

    <div style="margin: 4px 0 0 0; display: flex; justify-content: center">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="handleSubit" v-if="form.id"
        >提交</el-button
      >
      <el-button @click="homeDetail" type="warning" v-if="form.id"
        >预览</el-button
      >
    </div>
    <el-dialog
      :visible.sync="visible"
      width="60%"
      append-to-body
      @close="onReset"
    >
      <el-form ref="form" :model="formItem" label-width="160px">
        <el-form-item label="场次名称">
          <el-input v-model="formItem.activityTimeName"></el-input>
        </el-form-item>
        <el-form-item label="英文场次名称">
          <el-input v-model="formItem.activityTimeNameEn"></el-input>
        </el-form-item>
        <el-form-item label="场次起始时间">
          <el-time-picker
            v-model="formItem.activityBeginTime"
            placeholder="选择时间"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="场次结束时间">
          <el-time-picker
            v-model="formItem.activityEndTime"
            placeholder="选择时间"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="取号起始时间" v-if="activityType == 1">
          <el-time-picker
            v-model="formItem.queueBeginTime"
            placeholder="选择时间"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="取号结束时间" v-if="activityType == 1">
          <el-time-picker
            v-model="formItem.queueEndTime"
            placeholder="选择时间"
            value-format="HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="限制人数">
          <el-input-number
            v-model="formItem.limitPeopleNum"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="限制入场年龄" v-if="activityType != 1">
          <el-input-number v-model="formItem.minAge" :min="0"></el-input-number>
          <span>&nbsp;至&nbsp;</span>
          <el-input-number v-model="formItem.maxAge" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <div style="margin-top: 4px; display: flex; justify-content: center">
        <el-button type="primary" @click="onSave">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="提交一级审核"
      :visible.sync="open2"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form2" label-width="100px">
        <template>
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="默认" name="first">
              <el-select v-model="form2.nextEmp" placeholder="请选择">
                <el-option
                  v-for="item in nextEmpList"
                  :key="item.userId"
                  :label="item.userId + '-' + item.userCnName"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="firstSubmit" type="primary">提交</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  create,
  edit,
  detail,
  audit,
  actionLog,
  listUsers,
} from "@/api/activityConfiguration";
import { getListByParentId } from "@/api/activityMenu";
import WangEditor from "wangeditor";
export default {
  props: ["activityType"],
  data() {
    return {
      activeName: "first",
      activityMenuList: [],
      // 添加活动菜单缓存，格式为: {parentId: [{label, value}]}
      activityMenuCache: {},
      form: {
        id: null,
        activityName: "",
        sort: "",
        wapImgUrl: "",
        pcImgUrl: "",
        queuingInstructions: "",
        activityIntroduce: "",
        activityPlace: "",
        activityNameEn: "",
        queuingInstructionsEn: "",
        activityIntroduceEn: "",
        activityPlaceEn: "",
        activityTimeList: [],
        activityStartTime: "",
        activityReservationStartTime: "",
        activityReservationEndTime: "",
        isParentChild: "",
        isCharge: "",
        activityMenuId: "",
      },
      formItem: {
        id: "",
        activityTimeName: "",
        activityTimeNameEn: "",
        activityBeginTime: "",
        activityEndTime: "",
        queueBeginTime: "",
        queueEndTime: "",
        limitPeopleNum: "",
        minAge: "",
        maxAge: "",
      },
      visible: false,
      isEdit: -1,
      editor: null,
      editorEn: null,

      actionLogList: [],
      form2: {
        id: null,
        nextEmp: null,
      },
      nextEmpList: [],
      open2: false,
    };
  },
  watch: {
    activeName() {
      if (this.activeName == "second") {
        if (!this.editorEn) {
          this.$nextTick(() => {
            this.editorEn = new WangEditor(this.$refs.editorContainerEn);
            this.editorEn.create();
            this.editorEn.cmd.do("insertHTML", this.form.activityIntroduceEn);
          });
        }
      }
    },
    activityType: {
      handler(newVal) {
        if (newVal && newVal != "1") {
          this.loadActivityMenus(newVal);
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.installEditor();
      // 如果不是互动体验，加载活动类型
      if (this.activityType != "1") {
        this.loadActivityMenus(this.activityType);
      }
    });
  },
  methods: {
    // 加载活动类型列表
    loadActivityMenus(parentId) {
      // 打印日志便于调试
      console.log('加载活动类型列表，parentId:', parentId);
      
      // 检查缓存中是否已有该parentId的数据
      if (this.activityMenuCache[parentId]) {
        console.log('使用缓存的活动类型列表');
        this.activityMenuList = this.activityMenuCache[parentId];
        return;
      }
      
      // 直接传递parentId
      getListByParentId(parentId).then(res => {
        if (res.code === 200) {
          // 处理返回的rows数据，将menuName映射为label，id映射为value
          const menuList = (res.rows || []).map(item => ({
            label: item.menuName,
            value: item.id
          }));
          
          // 保存到缓存
          this.activityMenuCache[parentId] = menuList;
          this.activityMenuList = menuList;
          
          console.log('活动类型列表:', this.activityMenuList);
        } else {
          console.error('获取活动类型列表失败:', res.msg);
        }
      }).catch(error => {
        console.error('请求活动类型列表出错:', error);
      });
    },
    onDetail(id) {
      this.form.id = id;
      detail(id).then((res) => {
        for (let key in this.form) {
          this.form[key] = res.data[key];
        }
        this.editor.cmd.do("insertHTML", this.form.activityIntroduce);
        this.editorEn.cmd.do("insertHTML", this.form.activityIntroduceEn);

        const queryParams = {
          bizId: this.form.id,
          module: "activity",
          pageNum: 1,
          pageSize: 999,
        };
        actionLog(queryParams).then((res) => {
          this.actionLogList = res.rows;
        });
      });
    },
    onSubmit() {
      const fn = this.form.id ? edit : create;
      this.form.activityIntroduce = this.editor.txt.html();
      this.form.activityIntroduceEn =
        this.editorEn?.txt.html() || this.form.activityIntroduceEn;
      
      // 如果activityType不是"1"，则统一设置为"2"
      const realActivityType = this.activityType === "1" ? "1" : "2";
      
      const data = {
        ...this.form,
        activityType: realActivityType,
      };
      fn(data).then((res) => {
        this.$emit("success");
      });
    },
    onCancel() {
      this.$emit("cancel");
    },
    onAdd() {
      this.visible = true;
      // 如果不是互动体验类型，立即请求活动类型列表
      if (this.activityType != "1") {
        this.loadActivityMenus(this.activityType);
      }
    },
    onEdit(row, index) {
      for (let key in this.formItem) {
        this.formItem[key] = row[key];
      }
      this.isEdit = index;
      this.visible = true;
      // 如果不是互动体验类型，立即请求活动类型列表
      if (this.activityType != "1") {
        this.loadActivityMenus(this.activityType);
      }
    },
    onSave() {
      if (this.isEdit == -1) {
        this.form.activityTimeList.push({ ...this.formItem });
      } else {
        this.form.activityTimeList.splice(this.isEdit, 1, { ...this.formItem });
      }
      this.visible = false;
    },
    onDelete(index) {
      this.form.activityTimeList.splice(index, 1);
    },
    onReset() {
      this.isEdit = -1;
      for (let key in this.formItem) {
        this.formItem[key] = null;
      }
    },
    installEditor() {
      this.editor = new WangEditor(this.$refs.editorContainer);
      this.editor.create();
      this.editor.cmd.do("insertHTML", this.form.activityIntroduce);
    },

    async handleSubit() {
      this.form2.id = this.form.id;
      this.form2.nextEmp = null;
      this.nextEmpList = [];

      let res = await listUsers("kb", "reviewer_l1");
      if (res.code == 200) {
        this.nextEmpList = res.data;
      }

      this.open2 = true;
    },
    async firstSubmit() {
      let nextEmpName = this.nextEmpList.filter(
        (item) => item.userId == this.form2.nextEmp
      )[0].userCnName;
      let res = await audit(this.form2.id, this.form2.nextEmp, nextEmpName);
      if (res.code == 200) {
        this.open2 = false;
        const fn = this.form.id ? edit : create;
        this.form.activityIntroduce = this.editor.txt.html();
        this.form.activityIntroduceEn =
          this.editorEn?.txt.html() || this.form.activityIntroduceEn;
        
        // 如果activityType不是"1"，则统一设置为"2"
        const realActivityType = this.activityType === "1" ? "1" : "2";
        
        const data = {
          ...this.form,
          activityType: realActivityType,
        };
        fn(data).then((res) => {
          this.$emit("success");
        });
      }
    },
    async homeDetail() {
      if (this.activityType == 1) {
        window.open(
          "https://worldskillsmuseum.cn/#/active/detail?id=" + this.form.id
        );
      } else {
        window.open(
          "http://worldskillsmuseum.cn/#/active/gongfang-detail?id=" +
            this.form.id
        );
      }
    },
  },
};
</script>
